package com.example.thirdstage_project.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.thirdstage_project.common.Result2;
import com.example.thirdstage_project.entity.Unit;
import com.example.thirdstage_project.entity.User;
import com.example.thirdstage_project.common.Code;
import com.example.thirdstage_project.common.Result;
import com.example.thirdstage_project.ov.LoginVO;
import com.example.thirdstage_project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static cn.hutool.core.lang.Console.log;
import static com.example.thirdstage_project.utils.RedisConstants.LOGIN_USER_KEY;
import static com.example.thirdstage_project.utils.RedisConstants.LOGIN_USER_TTL;


/**
 * 统一登录用户信息表(User)表控制层
 *
 * @author makejava
 * @since 2022-11-22 16:32:32
 */
@Slf4j
@RestController
@RequestMapping("/users")
//@CrossOrigin(value = "http://localhost:8081",allowCredentials = "true")
//前端不需要走代理时打开或者全局配置
public class UserController {
    @Autowired
    private HttpSession session;
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 登录功能????
     * 保留session，退出时删除session
     */
//    @PostMapping("/login")
    public Result<User> login1(HttpServletRequest request,@RequestBody User user){
        String password = user.getPassword();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,user.getUsername());
        User user1 = userService.login1(queryWrapper);

        //查询
        if (user1 == null){
            //登录失败
            return new Result(Code.GET_ERR,null);
        }
        if (!user1.getPassword().equals(password)){
            //登陆失败
            return new Result(Code.GET_ERR,null);
        }
        //登录成功，将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("user",user.getUid());

        Integer code = user1 != null ? Code.GET_OK : Code.GET_ERR;
        String msg = user1 != null ? "" : "数据查询失败";
        return new Result(code,user,msg);
    }
    /**
     * 员工退出
     * @param
     * @return
     */
    @PostMapping("/logout")
    public Result2<User> logout(){
        //清理Session中保存的当前登录员工的id
        session.removeAttribute("user");
        return Result2.ok("退出成功");
    }


    /**
     *登录
     */
//    @PostMapping("/login")
    public Result login3(String username, String password){
        User user1 = userService.login2(username,password);
//        session.setAttribute("user",user1.getUid());
        Integer code = user1 != null ? Code.GET_OK : Code.GET_ERR;
        String msg = user1 != null ? "" : "数据查询失败";
        return new Result(code,user1,msg);
    }
    /**
     * 登录
     * redis
     */
    @PostMapping("/login")
    public Result login2(String username,String password){
        User user1 = userService.login2(username,password);
//        session.setAttribute("user",user.getUid());
        //redis
        //1.随机生成token，作为为登录令牌
        String token = UUID.randomUUID().toString(true);
        //2.将user对象转为hash存储
        LoginVO loginVO = BeanUtil.copyProperties(user1,LoginVO.class);
        Map<String, Object> map = BeanUtil.beanToMap(loginVO);
        //储存
        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY+token,map);
        //设置有效期
        stringRedisTemplate.expire(LOGIN_USER_KEY+token,LOGIN_USER_TTL, TimeUnit.MINUTES);

        Integer code = user1 != null ? Code.GET_OK : Code.GET_ERR;
        String msg = user1 != null ? "数据查询成功" : "数据查询失败";
        return new Result(token,code,user1,msg);
    }

    /**
     * 查询所有
     * @return
     */
//    @GetMapping("/all")
    public Result selectAll(){
        List<User> user = userService.getAll();
        Integer code = user != null ? Code.GET_OK : Code.GET_ERR;
        String msg = user != null ? "数据查询成功" : "数据查询失败";
        return new Result(code,user,msg);
    }


    /**
     * 根据uid删除
     */
    @DeleteMapping("/{uid}")
    public Result delete(@PathVariable Integer uid){
        boolean save = userService.delete(uid);
        return new Result(save ? Code.DELETE_OK: Code.DELETE_ERR ,save);
    }
    /**
     * 添加
     */
    @PostMapping
    public Result save(@RequestBody User user){
        boolean save = userService.save(user);
        return new Result(save ? Code.SAVE_OK : Code.SAVE_ERR,save);
    }
    /**
     * 分页
     * @return
     */
    @GetMapping("/all")
    public Result getPage2(int currentPage, int pageSize){
        IPage<User> page = userService.getPage(currentPage, pageSize);
        if (currentPage > page.getPages()){
            page = userService.getPage((int)page.getPages(), pageSize);
        }
        return new Result(Code.Page_OK,page);
    }

//    /**
//     * 更新用户信息
//     */
//    @PutMapping
//    public Result updateById(@RequestBody User user){
//        boolean save = userService.updateById(user);
//        return new Result(save ? Code.UPDATE_OK : Code.UPDATE_ERR,save);
//    }


    /**
     * 多表联查 user和usergroup
     * 登录用户管理界面
     */
    @GetMapping("/userManagement")
    public Result listByName(){
        List<LoginVO> userOVS = userService.listByName();
        Integer code = userOVS != null ? Code.GET_OK : Code.GET_ERR;
        String msg = userOVS != null ? "" : "数据查询失败";
        return new Result(code,userOVS,msg);
    }


//    /**
//     * 修改密码
//     */
//    @PutMapping
//    public Result updatePassword(String password){
//        boolean update = userService.updatePassword(password);
//        return new Result(update ? Code.UPDATE_OK : Code.UPDATE_ERR,update);
//    }

    @PostMapping("/option")
    public Result update(String username,String password,int gid){
        boolean save = userService.updateOption(username,password,gid);
        return new Result(save ? Code.SAVE_OK : Code.SAVE_ERR,save);
    }

    @PostMapping("/updateEx")
    public Result updateEx(Unit unit){
        boolean save = userService.updateEx(unit);
        return new Result(save ? Code.SAVE_OK : Code.SAVE_ERR,save);
    }
}


